﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace WorldOfMUDra
{
    public class PasswordStorageFile
    {
        readonly string _fname;
        readonly string[] _lines;
        readonly Dictionary<string, string> _userPassDict = new Dictionary<string, string>();

        private void LoadDictionary()
        {
            try
            {
                foreach (string[] toks in _lines.Select(line => line.Split(' ')).Where(toks => toks.Length >= 2))
                {
                    Console.WriteLine("Adding username: " + toks[0] + " with password: " + toks[1]);
                    _userPassDict.Add(toks[0], toks[1]);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public PasswordStorageFile(string filename)
        {
            _fname = filename;
            try
            {
                _lines = File.ReadAllLines(_fname);
                LoadDictionary();
            }
            catch(Exception)
            {
                Console.WriteLine("Issues loading the file by name: "+filename);
            }
        }

        public static string CalculateMd5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = MD5.Create();
            byte[] inputBytes = Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            foreach (byte t in hash)
            {
                sb.Append(t.ToString("x2"));
            }
            return sb.ToString();
        }

        public string FileName
        {
            get { return _fname; }
        }

        public void AddUser(string name, string pass)
        {
            if (_userPassDict.ContainsKey(name)) return;
            string hashedPass = CalculateMd5Hash(pass);
            _userPassDict.Add(name, hashedPass);
            File.AppendAllText(_fname, (Environment.NewLine + name + ' ' + hashedPass + Environment.NewLine));
            Console.WriteLine("Adding username: " + name + " with ENCRYPTED password: " + hashedPass);
        }

        public bool VerifyPasswordOf(string name, string unhashedpass)
        {
            return (_userPassDict[name] == CalculateMd5Hash(unhashedpass));
        }

        public bool ContainsUser(string username)
        {
            return _userPassDict.ContainsKey(username);
        }
    }
}
